package com.coder520.login.controller;

import com.coder520.common.utils.SecurityUtils;
import com.coder520.user.entity.User;
import com.coder520.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

/**
 * Created by Administrator on 2017-7-7.
 */
@Controller
@RequestMapping("login")
public class LoginController {

    @Autowired
    private UserService userService;

    
    /**
      *@Author Jay 
      *@Date 2017-7-8 11:13
      *@Description     登入页面
      */
    @RequestMapping
    public String login() {
        return "login";
    }

    /**
      *@Author Jay
      *@Date 2017-7-8 11:14
      *@Description     校验登入
      */
    @RequestMapping("/check")
    @ResponseBody       //异步请求
    public String checkLogin(HttpServletRequest request) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        String username = request.getParameter("username");
        String pwd = request.getParameter("pwd");

        //查数据库
        User user = userService.findUserByUsername(username);
        if(user != null) {
            if(SecurityUtils.checkPassword(pwd,user.getPassword())) {
                //说明登入成功 ,设置session
                request.getSession().setAttribute("userInfo",user);
                return "login_succ";
            }else {
                return "login_fail";
            }
        }else {
            return "login_fail";
        }
        //校验成功  1,用户信息存session 2,进入首页
        //校验失败  页面给提示

    }

    @RequestMapping("/register")
    @ResponseBody
    public String register(@RequestBody User user) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        userService.createUser(user);
        return "register_success";
    }
}
